package com.qf.filter;

import com.alibaba.fastjson.JSON;
import com.qf.entity.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

@Component
public class FormSubmitFilter implements GatewayFilter, Ordered {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        System.out.println("防止重复提交的过滤器已经触发！");
        //获得请求 - get
        MultiValueMap<String, String> params = exchange.getRequest().getQueryParams();
        System.out.println(params);
        //表单提交的uuid
        String uuid = params.get("uuid").get(0);

        if (redisTemplate.hasKey(uuid)) {
            //存在

            ServerHttpResponse response = exchange.getResponse();

            R result = new R()
                    .setCode(R.CODE.ERROR)
                    .setMsg("请勿反复发送请求！");

            DataBuffer dataBuffer = null;
            try {
                response.getHeaders().add("Content-Type", "application/json;charset=utf-8");
                //解决跨域问题
                response.getHeaders().add("Access-Control-Allow-Origin", "*");
                dataBuffer = response.bufferFactory().wrap(JSON.toJSONString(result).getBytes("utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return response.writeWith(Mono.just(dataBuffer));
        } else {
            //不存在
            redisTemplate.opsForValue().set(uuid, "true");
            redisTemplate.expire(uuid, 10, TimeUnit.SECONDS);

            //放行
            return chain.filter(exchange);
        }
    }

    @Override
    public int getOrder() {
        return 100;
    }
}
